<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" class="search-form">
      <el-form-item>
        <el-input
          v-model="queryParams.operational_name"
          placeholder="请输入工艺路线名称"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-select v-model="queryParams.operational_status" placeholder="请选择状态" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 标题和操作按钮 -->
    <div class="title-container">
      <h4 class="title">工艺路线</h4>
    </div>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete(null, true)"
        >批量删除</el-button>
      </el-col>
    </el-row>

    <!-- 工艺路线表格 -->
    <el-table
      v-loading="loading"
      :data="routeList"
      @selection-change="handleSelectionChange"
      border
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="index" width="60">
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="工艺路线名称" align="center" prop="operational_name" />
      <el-table-column label="工艺路线编号" align="center" prop="operational_code">
          <template slot-scope="scope">
            <el-link type="primary" :underline="false" @click="handleViewDetail(scope.row)">{{ scope.row.operational_code }}</el-link>
          </template>
        </el-table-column>
      <el-table-column label="状态" align="center" prop="operational_status">
        <template slot-scope="scope">
          <el-tag :type="scope.row.operational_status == 0 ? 'danger' : 'success'">
            {{ scope.row.operational_status == 0 ? '停用' : '启用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="工艺路线说明" align="center" prop="operational_description" :show-overflow-tooltip="true" />
      <el-table-column label="备注" align="center" prop="remarks" :show-overflow-tooltip="true" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            class="blue-text"
          >编辑</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            class="red-text"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

          <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />

    <!-- 添加或修改工艺路线对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body>
      <el-tabs v-model="activeName" type="card" @tab-click="handleTabClick">
        <el-tab-pane label="基本信息" name="base">
          <el-form ref="form" :model="form" :rules="rules" label-width="120px">
            <el-form-item label="工艺路线名称" prop="operational_name">
              <el-input v-model="form.operational_name" placeholder="请输入工艺路线名称" />
              <div class="error-tip" v-if="form.operational_name === ''" style="color: #F56C6C; font-size: 12px; margin-top: 5px;">工艺路线名称不能为空</div>
            </el-form-item>
            <el-form-item label="工艺路线编号" prop="operational_code">
              <el-input v-model="form.operational_code" placeholder="请输入工艺路线编号" disabled>
                <!-- Removed the automatic numbering button -->
              </el-input>
              <div class="error-tip" v-if="form.operational_code === ''" style="color: #F56C6C; font-size: 12px; margin-top: 5px;">工艺路线编号不能为空</div>
            </el-form-item>
            <el-form-item>
              <el-switch
                v-model="isSystemCode"
                active-text="系统编号"
                inactive-text=""
                style="margin-top: 13px;"
                @change="handleSystemCodeChange"
                v-if="!title.includes('修改')"
              ></el-switch>
            </el-form-item>
            <el-form-item label="状态" prop="operational_status">
              <el-radio-group v-model="form.operational_status">
                <el-radio :label="1">启用</el-radio>
                <el-radio :label="0">停用</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="工艺路线说明" prop="operational_description">
              <el-input type="textarea" v-model="form.operational_description" placeholder="请输入工艺路线说明" />
            </el-form-item>
            <el-form-item label="备注" prop="remarks">
              <el-input type="textarea" v-model="form.remarks" placeholder="请输入备注" />
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <el-tab-pane label="关联产品" name="product">
          <div class="mb8">
            <el-button type="primary" icon="el-icon-plus" size="mini" plain @click="handleAddProduct">添加</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" plain :disabled="!selectedProduct" @click="handleRemoveProduct()">移除</el-button>
          </div>

          <el-table
            v-loading="productLoading"
            :data="productList"
            @selection-change="handleProductSelectionChange"
            @row-click="handleProductRowClick"
            border
          >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="序号" align="center" width="60">
              <template slot-scope="scope">
                {{ scope.$index + 1 }}
              </template>
            </el-table-column>
            <el-table-column type="expand">
              <template slot-scope="props">
                <el-table
                  :data="props.row.processList || []"
                  border
                  style="width: 100%"
                >
                  <el-table-column label="序号" align="center" prop="sequence" width="80" />
                  <el-table-column label="工序编号" align="center" prop="process_code" />
                  <el-table-column label="工序名称" align="center" prop="process_name" />
                  <el-table-column label="下一道工序" align="center" prop="next_process_name">
                    <template slot-scope="scope">
                      {{ scope.row.next_process_name || '无下道工序' }}
                    </template>
                  </el-table-column>
                  <!-- 根据是否为编辑模式显示不同的列 -->
                  <template v-if="title.includes('修改')">
                    <!-- 编辑模式下显示的列 -->
                    <el-table-column label="工序状态" align="center" prop="process_status">
                      <template slot-scope="scope">
                        <el-tag :type="getProcessStatusType(scope.row.process_status)">
                          {{ getProcessStatusText(scope.row.process_status) }}
                        </el-tag>
                      </template>
                    </el-table-column>
                    <el-table-column label="工序说明" align="center" prop="process_description" :show-overflow-tooltip="true" />
                  </template>
                  <template v-else>
                    <!-- 新增模式下显示的列 -->
                  <el-table-column label="关系" align="center" prop="relation_type" />
                  <el-table-column label="关键工序" align="center">
                    <template slot-scope="scope">
                      {{ scope.row.is_key === 1 ? '是' : '否' }}
                    </template>
                  </el-table-column>
                  <el-table-column label="颜色" align="center" width="80">
                    <template slot-scope="scope">
                      <div class="color-box" :style="{ backgroundColor: scope.row.color }"></div>
                      <span>{{ scope.row.color }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="准备时间" align="center">
                    <template slot-scope="scope">
                      {{ scope.row.prepare_time }} 小时
                    </template>
                  </el-table-column>
                  <el-table-column label="等待时间" align="center">
                    <template slot-scope="scope">
                      {{ scope.row.wait_time }} 小时
                    </template>
                  </el-table-column>
                  </template>
                  <el-table-column label="操作" align="center" width="150">
                    <template slot-scope="scope">
                      <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-delete"
                        @click.stop="handleRemoveProcess(props.row, scope.row)"
                        class="red-text"
                      >删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <div v-if="!(props.row.processList && props.row.processList.length > 0)" class="no-data">
                  <span>暂无工序数据</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="产品ID" align="center" prop="product_id" width="150" show-overflow-tooltip>
              <template slot-scope="scope">
                <el-tooltip effect="dark" :content="scope.row.product_id" placement="top">
                  <span>{{ scope.row.product_id }}</span>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column label="产品编号" align="center" prop="product_code" />
            <el-table-column label="产品名称" align="center" prop="product_name" />
            <el-table-column label="规格型号" align="center" prop="specification" />
            <el-table-column label="单位" align="center" prop="unit" />
            <el-table-column label="BOM编号" align="center" prop="bom_code" />
            <el-table-column label="BOM版本" align="center" prop="bom_version" />
            <el-table-column label="工序数量" align="center">
              <template slot-scope="scope">
                {{ scope.row.processList ? scope.row.processList.length : 0 }}
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180">
              <template slot-scope="scope">
                <el-button size="mini" type="text" icon="el-icon-plus" @click.stop="handleAddProcessForProduct(scope.row)" class="blue-text">添加工序</el-button>
                <el-button size="mini" type="text" icon="el-icon-delete" @click.stop="handleRemoveProduct(scope.row)" class="red-text">移除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>

      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 工序选择对话框 -->
    <el-dialog title="选择工序" :visible.sync="processSelectVisible" width="800px" append-to-body>
      <el-form :inline="true" :model="processQuery" class="search-form">
        <el-form-item>
          <el-input v-model="processQuery.name" placeholder="请输入工序名称" clearable size="small" @keyup.enter.native="searchProcess" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="searchProcess">查询</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetProcessQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table
        v-loading="processSelectLoading"
        :data="processSelectList"
        @selection-change="handleProcessSelectChange"
        ref="processSelectTable"
        border
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="工序编号" align="center" prop="process_code" />
        <el-table-column label="工序名称" align="center" prop="process_name" />
        <el-table-column label="工序描述" align="center" prop="process_description" :show-overflow-tooltip="true" />
      </el-table>
      <pagination
        v-show="processSelectTotal > 0"
        :total="processSelectTotal"
        :page.sync="processQuery.pageNum"
        :limit.sync="processQuery.pageSize"
        @pagination="getProcessList"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="processSelectVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmSelectProcess">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 产品选择对话框 -->
    <el-dialog title="选择产品" :visible.sync="productSelectVisible" width="800px" append-to-body>
      <el-form :inline="true" :model="productQuery" class="search-form">
        <el-form-item>
          <el-input v-model="productQuery.name" placeholder="请输入产品名称" clearable size="small" @keyup.enter.native="searchProduct" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="searchProduct">查询</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetProductQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-alert
        v-if="productList.length > 0"
        :title="`已添加的产品将以灰色背景显示，且无法重复选择。当前已添加${productList.length}个产品。`"
        type="info"
        :closable="false"
        show-icon
        style="margin-bottom: 15px"
      />
      <el-table
        v-loading="productSelectLoading"
        :data="productSelectList"
        @selection-change="handleProductSelectChange"
        ref="productSelectTable"
        border
        :reserve-selection="true"
        row-key="product_id"
        :row-class-name="getRowClassName"
      >
        <el-table-column type="selection" width="55" align="center" :selectable="row => !row.isAlreadySelected" />
        <el-table-column label="产品ID" align="center" prop="product_id" width="150" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-tooltip effect="dark" :content="scope.row.product_id || '无ID'" placement="top">
              <span>{{ scope.row.product_id || '无ID' }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="产品编号" align="center" prop="product_code" show-overflow-tooltip />
        <el-table-column label="产品名称" align="center" prop="product_name" show-overflow-tooltip />
        <el-table-column label="规格型号" align="center" prop="specification" show-overflow-tooltip />
        <el-table-column label="单位" align="center" prop="unit" />
        <el-table-column label="BOM编号" align="center" prop="bom_code" show-overflow-tooltip />
        <el-table-column label="BOM版本" align="center" prop="bom_version" />
        <el-table-column label="状态" align="center" width="100">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.isAlreadySelected" type="info">已添加</el-tag>
            <el-tag v-else-if="!scope.row.product_id" type="danger">无ID</el-tag>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="productSelectTotal > 0"
        :total="productSelectTotal"
        :page.sync="productQuery.pageNum"
        :limit.sync="productQuery.pageSize"
        @pagination="getProductList"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="productSelectVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmSelectProduct">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 工序编辑对话框 -->
    <el-dialog :title="processTitle" :visible.sync="processOpen" width="600px" append-to-body>
      <el-form ref="processForm" :model="processForm" :rules="processRules" label-width="120px">
        <el-form-item label="序号" prop="sequence" required>
          <el-tooltip content="序号自动获取自工序ID，不可手动修改" placement="top">
            <el-input v-model="processForm.sequence" placeholder="自动获取自工序ID" style="width: 100%" readonly disabled />
          </el-tooltip>
        </el-form-item>

        <el-form-item label="工序" prop="process_id" required>
          <el-select v-model="processForm.process_id" placeholder="请选择工序" style="width: 100%"
            @change="handleProcessChange" filterable>
            <el-option
              v-for="item in processOptions"
              :key="item.process_id || item.processId"
              :label="item.process_name || item.processName"
              :value="item.process_id || item.processId"
            >
              <span>{{ (item.process_code || item.processCode || '') }} - {{ (item.process_name || item.processName || '未命名工序') }}</span>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="下一道工序" prop="next_process_id">
          <el-select v-model="processForm.next_process_id" placeholder="无下道工序" style="width: 100%" filterable @change="handleNextProcessChange">
            <el-option label="无下道工序" :value="null"></el-option>
            <el-option
              v-for="item in processOptions.filter(p => (p.process_id || p.processId) !== processForm.process_id)"
              :key="item.process_id || item.processId"
              :label="item.process_name || item.processName"
              :value="item.process_id || item.processId"
            >
              <span>{{ (item.process_code || item.processCode || '') }} - {{ (item.process_name || item.processName || '未命名工序') }}</span>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="关系" prop="relation_type" required>
          <el-select v-model="processForm.relation_type" placeholder="请选择与下一道工序关系" style="width: 100%">
            <el-option :label="'S-S'" :value="'S-S'"></el-option>
            <el-option :label="'F-F'" :value="'F-F'"></el-option>
            <el-option :label="'S-F'" :value="'S-F'"></el-option>
            <el-option :label="'F-S'" :value="'F-S'"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="关键工序" prop="is_key" required>
          <el-radio-group v-model="processForm.is_key">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="显示颜色" prop="color" required>
          <el-color-picker v-model="processForm.color"></el-color-picker>
          <el-input v-model="processForm.color" style="width: 240px; margin-left: 10px;" :disabled="true"></el-input>
        </el-form-item>

        <el-form-item label="准备时间" prop="prepare_time">
          <div class="time-input-container">
            <el-input-number v-model="processForm.prepare_time" :min="0" :precision="2" :step="0.1" controls-position="right" style="width: 220px;" />
            <span class="time-unit">小时</span>
          </div>
        </el-form-item>

        <el-form-item label="等待时间" prop="wait_time">
          <div class="time-input-container">
            <el-input-number v-model="processForm.wait_time" :min="0" :precision="2" :step="0.1" controls-position="right" style="width: 220px;" />
            <span class="time-unit">小时</span>
          </div>
        </el-form-item>

        <el-form-item label="备注" prop="remarks">
          <el-input type="textarea" v-model="processForm.remarks" placeholder="请输入" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelProcess">取 消</el-button>
        <el-button type="primary" @click="submitProcessForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRoute, getRoute, delRoute, delRoutes, addRoute, updateRoute, listBomdetailsVoByOperationalIdIsNull, listpro, listopdetails, listop1 } from "@/api/sc/operational";
import { getAutoNumbers, getAutoNumbersConsume } from "@/api/basic/numbers";
import { listProcess } from "@/api/sc/process";
import { listBom } from "@/api/basic/bom";

export default {
  name: "ScOperational",
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 工艺路线表格数据
      routeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 选中的工序列表
      selectedProcesses: [],
      // 选中的产品列表
      selectedProducts: [],
      // 状态选项
      statusOptions: [
        {
          value: 1,
          label: "启用"
        },
        {
          value: 0,
          label: "停用"
        }
      ],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        operational_name: undefined,  // 文本框的值
        operational_status: undefined  // 下拉框的值
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        operational_name: [
          { required: true, message: "工艺路线名称不能为空", trigger: "blur" }
        ],
        operational_code: [
          { required: true, message: "工艺路线编号不能为空", trigger: "blur" }
        ],
        operational_status: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ]
      },
      // 工序相关
      processLoading: false,
      processList: [],
      selectedProcess: null,
      processSelectVisible: false,
      processSelectLoading: false,
      processSelectList: [],
      processQuery: {
        pageNum: 1,
        pageSize: 10,
        name: undefined
      },
      processSelectTotal: 0,
      processOptions: [],
      processOpen: false,
      processForm: {
        process_id: undefined,
        process_name: undefined,
        process_code: undefined,
        sequence: '',
        next_process_id: null,
        next_process_name: '无下道工序',
        relation_type: 'S-S',
        is_key: 0,
        prepare_time: 0,
        wait_time: 0,
        color: '#1B9AEE',
        remarks: ''
      },
      processRules: {
        sequence: [{ required: true, message: "序号不能为空", trigger: "blur" }],
        process_id: [{ required: true, message: "工序不能为空", trigger: "change" }],
        relation_type: [{ required: true, message: "工序关系不能为空", trigger: "change" }],
        is_key: [{ required: true, message: "是否关键工序不能为空", trigger: "change" }],
        prepare_time: [{ type: 'number', min: 0, message: '准备时间不能小于0', trigger: 'blur' }],
        wait_time: [{ type: 'number', min: 0, message: '等待时间不能小于0', trigger: 'blur' }],
        color: [{ required: true, message: '颜色不能为空', trigger: 'change' }]
      },
      // 产品相关
      productLoading: false,
      productList: [], // 确保初始化为空数组
      selectedProduct: null,
      productSelectVisible: false,
      productSelectLoading: false,
      productSelectList: [],
      productQuery: {
        pageNum: 1,
        pageSize: 10,
        name: undefined
      },
      productSelectTotal: 0,
      // 当前正在操作的产品
      currentProduct: null,
      // 当前步骤
      active: 0,
      // 工序编辑对话框标题
      processTitle: '',
      // 添加或修改工艺路线对话框的标签页
      activeName: 'base',
      // 工序编辑对话框的标签页
      processActiveName: 'processBase',
      // 已删除的产品ID列表，用于提交时解除BOM明细关联
      deletedProductIds: [],
      // 是否使用系统编号
      isSystemCode: false,
    };
  },
  created() {
    this.handleQuery();
  },
  mounted() {
    // 初始化时预加载工序选项
    this.getProcessOptions();
  },
  watch: {
    // 监听路由变化，页面重新加载时刷新数据
    '$route'(to) {
      if (to.path === '/sc/operational' || to.name === 'ScOperational') {
        console.log('生产运营页面路由变化，刷新数据');
        this.handleQuery();
      }
    },
    // 监听标签页切换
    activeName(newVal, oldVal) {
      // 当切换到"关联产品"标签页时，如果是编辑模式并且有operational_id，则加载产品数据
      if (newVal === 'product' && oldVal === 'base' && this.form.operational_id) {
        this.loadProductsAndProcesses(this.form.operational_id);
      }
    },
    // 监听查询参数变化
    queryParams: {
      handler(newVal, oldVal) {
        if (oldVal && JSON.stringify(newVal) !== JSON.stringify(oldVal)) {
          console.log('生产运营查询参数变化，刷新数据');
          this.handleQuery();
        }
      },
      deep: true
    }
  },
  methods: {
    /** 加载产品和工序信息 */
    loadProductsAndProcesses(id) {
      console.log("正在加载产品和工序信息，工艺路线ID:", id);
      this.productLoading = true;
      listopdetails(id).then(response => {
        console.log("获取工艺路线关联产品数据:", response);

        // 详细记录返回的数据结构
        if (response) {
          console.log("返回数据类型:", typeof response);
          console.log("返回数据顶级字段:", Object.keys(response));

          if (response.data) {
            console.log("data字段类型:", typeof response.data);
            if (Array.isArray(response.data)) {
              console.log("data是数组，长度:", response.data.length);
              if (response.data.length > 0) {
                console.log("第一条记录的字段:", Object.keys(response.data[0]));
              }
            } else if (typeof response.data === 'object') {
              console.log("data是对象，字段:", Object.keys(response.data));
            }
          }

          if (response.rows) {
            console.log("rows字段类型:", typeof response.rows);
            if (Array.isArray(response.rows)) {
              console.log("rows是数组，长度:", response.rows.length);
              if (response.rows.length > 0) {
                console.log("第一条记录的字段:", Object.keys(response.rows[0]));
              }
            }
          }
        }

        // 检查返回的数据结构
        if (response.data || response.rows) {
          let rawData = response.data || response.rows;

          // 处理多种可能的数据格式
          if (Array.isArray(rawData)) {
            // 直接得到数组，需要按产品进行分组
            console.log("接收到原始数据数组，长度:", rawData.length);

            // 按产品ID分组数据
            const productMap = new Map();

            rawData.forEach(item => {
              const productId = item.product_id;
              if (!productId) {
                console.warn("发现没有product_id的记录:", item);
                return;
              }

              if (!productMap.has(productId)) {
                // 创建新的产品对象，详细记录每个字段
                console.log("正在处理产品ID:", productId, "产品名称:", item.product_name || "未知");

                // 提取所有可能的产品相关字段
                productMap.set(productId, {
                  product_id: productId,
                  product_code: item.product_code,
                  product_name: item.product_name,
                  specification: item.product_sfn || item.specification,
                  unit: item.product_unit || item.unit,
                  bom_code: item.bom_code,
                  bom_version: item.bom_version,
                  bom_id: item.bom_id,
                  processList: [],
                  processMap: new Map() // 用于临时存储工序ID到工序对象的映射
                });
              }

              // 如果有工序信息，添加到产品的工序列表
              if (item.process_id) {
                const product = productMap.get(productId);
                console.log("为产品", productId, "添加工序:", item.process_id, item.process_name || "未知工序名");

                // 检查是否已有该工序
                if (!product.processList.some(p => p.process_id === item.process_id)) {
                  // 从数据行提取工序信息的所有可能字段
                  const processItem = {
                    process_id: item.process_id,
                    process_code: item.process_code,
                    process_name: item.process_name,
                    sequence: item.sequence || item.operationaldetails_id || item.process_id.toString(),
                    next_process_id: item.next_process_id || null,
                    next_process_name: item.next_process_name || '无下道工序',
                    relation_type: item.relation_type || 'S-S',
                    is_key: item.is_key || 0,
                    prepare_time: item.prepare_time || 0,
                    wait_time: item.wait_time || 0,
                    color: item.color || '#409EFF',
                    process_status: item.process_status !== undefined ? item.process_status : 1,
                    process_description: item.process_description || '',
                    remarks: item.remarks || '',
                    station_id: item.station_id
                  };

                  product.processList.push(processItem);
                  // 同时存储到Map中，方便后续查找
                  product.processMap.set(processItem.process_id.toString(), processItem);
                  console.log("已添加工序:", processItem);
                }
              }
            });

            // 转换Map为数组
            this.productList = Array.from(productMap.values());

            // 处理每个产品的工序列表，设置正确的next_process_name
            this.productList.forEach(product => {
              // 删除临时的processMap
              const processMap = product.processMap;
              delete product.processMap;

              // 根据模式处理下一道工序名称
              if (this.title.includes('修改')) {
                // 编辑模式：使用辅助方法更新工序关系
                this.updateProductProcessRelationships(product);
              } else {
                // 非编辑模式，使用原始的next_process_id查找方式
                // 创建工序ID到工序对象的映射
                const processMap = new Map();
                product.processList.forEach(process => {
                  processMap.set(process.process_id.toString(), process);
                });

                // 更新每个工序的next_process_name
                product.processList.forEach(process => {
                  if (process.next_process_id) {
                    // 如果有下一道工序ID，从Map中查找对应的工序对象
                    const nextProcess = processMap.get(process.next_process_id.toString());
                    if (nextProcess) {
                      // 设置下一道工序名称为实际的工序名称
                      process.next_process_name = nextProcess.process_name;
                    }
                  } else {
                    // 确保无下道工序时显示为"无下道工序"
                    process.next_process_name = '无下道工序';
                  }

                  // 确保工序状态和说明字段存在
                  if (process.process_status === undefined) {
                    process.process_status = 1; // 默认为启用状态
                  }
                  if (!process.process_description) {
                    process.process_description = '';
                  }
                });
              }
            });

            console.log("处理后的产品列表:", this.productList);
          } else if (rawData.productList && Array.isArray(rawData.productList)) {
            // 如果直接返回了productList数组，使用它
            this.productList = rawData.productList;

            // 确保每个产品都有processList数组
            this.productList.forEach(product => {
              if (!product.processList) {
                this.$set(product, 'processList', []);
              } else if (product.processList.length > 0) {
                // 按序号对工序进行排序，确保顺序正确
                product.processList.sort((a, b) => {
                  // 使用序号排序时，尝试保持原始顺序，只有当序号不同时才排序
                  const seqA = parseInt(a.sequence) || 0;
                  const seqB = parseInt(b.sequence) || 0;
                  if (seqA !== seqB) {
                    return seqA - seqB;
                  }
                  // 如果序号相同，保持原有顺序
                  return 0;
                });

                // 根据模式处理下一道工序名称
                if (this.title.includes('修改')) {
                  // 编辑模式：使用辅助方法更新工序关系
                  this.updateProductProcessRelationships(product);
                } else {
                  // 非编辑模式，使用原始的next_process_id查找方式
                  // 创建工序ID到工序对象的映射
                  const processMap = new Map();
                  product.processList.forEach(process => {
                    processMap.set(process.process_id.toString(), process);
                  });

                  // 更新每个工序的next_process_name
                  product.processList.forEach(process => {
                    if (process.next_process_id) {
                      // 如果有下一道工序ID，从Map中查找对应的工序对象
                      const nextProcess = processMap.get(process.next_process_id.toString());
                      if (nextProcess) {
                        // 设置下一道工序名称为实际的工序名称
                        process.next_process_name = nextProcess.process_name;
                      }
                    } else {
                      // 确保无下道工序时显示为"无下道工序"
                      process.next_process_name = '无下道工序';
                    }

                    // 确保工序状态和说明字段存在
                    if (process.process_status === undefined) {
                      process.process_status = 1; // 默认为启用状态
                    }
                    if (!process.process_description) {
                      process.process_description = '';
                    }
                  });
                }
              }
            });
          } else if (typeof rawData === 'object') {
            // 如果是单个对象，将它转换为数组
            const product = {
              product_id: rawData.product_id,
              product_code: rawData.product_code,
              product_name: rawData.product_name,
              specification: rawData.product_sfn,
              unit: rawData.product_unit,
              bom_code: rawData.bom_code,
              bom_version: rawData.bom_version,
              processList: []
            };

            if (rawData.process_id) {
              product.processList.push({
                process_id: rawData.process_id,
                process_code: rawData.process_code,
                process_name: rawData.process_name,
                sequence: rawData.sequence || rawData.process_id.toString(),
                next_process_id: rawData.next_process_id || null,
                next_process_name: rawData.next_process_name || '无下道工序',
                relation_type: rawData.relation_type || 'S-S',
                is_key: rawData.is_key || 0,
                prepare_time: rawData.prepare_time || 0,
                wait_time: rawData.wait_time || 0,
                color: rawData.color || '#409EFF',
                process_status: rawData.process_status !== undefined ? rawData.process_status : 1,
                process_description: rawData.process_description || '',
                remarks: rawData.remarks || ''
              });
            }

            this.productList = [product];
          } else {
            console.warn("未能识别的数据格式:", rawData);
            this.productList = [];
          }
        } else {
          console.warn("获取工艺路线关联产品数据返回为空");
          this.productList = [];
        }

        // 检查产品列表的长度
        console.log("最终产品列表长度:", this.productList.length);
        if (this.productList.length === 0) {
          this.$message.warning("未找到关联产品数据");
        }
      }).catch(error => {
        console.error("获取工艺路线关联产品数据失败:", error);
        this.$modal.msgError("加载产品数据失败");
        this.productList = [];
      }).finally(() => {
        this.productLoading = false;
      });
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;

      // 确保输入的值能传递到后端
      console.log("查询条件：", {
        工艺路线名称: this.queryParams.operational_name,
        状态: this.queryParams.operational_status
      });

      // 显式创建一个查询对象
      const params = {
        pageNum: this.queryParams.pageNum,
        pageSize: this.queryParams.pageSize,
        operational_name: this.queryParams.operational_name, // 文本框的值
        operational_status: this.queryParams.operational_status // 下拉框的值
      };

      // 直接调用API方法，不经过getList
      this.loading = true;
      listRoute(params)
        .then(response => {
          this.routeList = response.rows || [];
          this.total = response.total || 0;
        })
        .catch(error => {
          console.error("查询出错：", error);
          this.$message.error("查询失败，请查看控制台错误信息");
        })
        .finally(() => {
          this.loading = false;
        });
    },

    /** 查询工艺路线列表 */
    getList() {
      this.loading = true;
      // 确保查询参数正确传递
      const query = {...this.queryParams};

      // 打印查询参数，便于调试
      console.log("发送查询请求，参数:", JSON.stringify(query));

      listRoute(query).then(response => {
        this.routeList = response.rows || [];
        this.total = response.total || 0;
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        operational_id: undefined,
        operational_name: undefined,
        operational_code: undefined,
        operational_status: 1,
        operational_description: undefined,
        remarks: undefined,
        // 确保这些列表被初始化为空数组，而不是undefined
        processList: [],
        productList: []
      };
      // 确保这些组件级变量也被重置
      this.processList = [];
      this.selectedProcess = null;
      this.productList = [];
      this.selectedProduct = null;
      this.selectedProducts = [];
      this.deletedProductIds = []; // 清空已删除产品ID列表
      this.active = 0;
      this.resetForm("form");

      // 记录重置后的状态
      console.log("重置后的表单状态:", {
        form: {...this.form},
        processList: this.processList.length,
        productList: this.productList.length,
        selectedProducts: this.selectedProducts.length,
        deletedProductIds: this.deletedProductIds.length
      });
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      // 手动清空查询参数
      this.queryParams.operational_name = undefined;
      this.queryParams.operational_status = undefined;

      // 打印重置后的查询参数，便于调试
      console.log("重置查询参数:", JSON.stringify(this.queryParams));

      // 重新查询
      this.handleQuery();
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.operational_id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 生成工艺路线编号 */
    generateRouteCode() {
      getAutoNumbers(32).then(response => {
        console.log("自动编号返回数据:", response);
        if (response && typeof response === 'string') {
          // 直接使用返回的字符串值
          this.form.operational_code = response;
        } else if (response && response.data) {
          // 使用返回的data字段值
          this.form.operational_code = response.data;
        } else if (response && response.msg) {
          // 部分接口可能在msg中返回数据
          this.form.operational_code = response.msg;
        } else {
          // 如果没有返回有效数据，则生成格式为"GYLX"+日期格式的编号
          const now = new Date();
          const year = now.getFullYear();
          const month = String(now.getMonth() + 1).padStart(2, '0');
          const day = String(now.getDate()).padStart(2, '0');
          const num = Math.floor(Math.random() * 100).toString().padStart(2, '0');
          this.form.operational_code = `GYLX${year}${month}${day}${num}`;
        }
      }).catch(error => {
        console.error("获取自动编号失败:", error);
        // 发生错误时使用后备方案生成编号
        const now = new Date();
        const year = now.getFullYear();
        const month = String(now.getMonth() + 1).padStart(2, '0');
        const day = String(now.getDate()).padStart(2, '0');
        const num = Math.floor(Math.random() * 100).toString().padStart(2, '0');
        this.form.operational_code = `GYLX${year}${month}${day}${num}`;
      });
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加工艺路线";
      this.activeName = 'base'; // 重置步骤
      
      // 如果启用系统编号，自动生成编号
      if (this.isSystemCode) {
        this.generateRouteCode();
      }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.operational_id || this.ids[0];

      // 创建查询对象
      const query = {
        operational_id: id
      };

      // 使用listRoute替代getRoute获取工艺路线信息
      listRoute(query).then(response => {
        // 从response.rows中获取第一条记录
        if (response.rows && response.rows.length > 0) {
          this.form = response.rows[0] || {};

        // 确保状态是数字类型
        if (this.form.operational_status !== undefined) {
          this.form.operational_status = parseInt(this.form.operational_status);
        }

        this.open = true;
        this.title = "修改工艺路线";
        this.activeName = 'base'; // 重置步骤

          // 预加载产品和工序数据
          if (this.form.operational_id) {
            this.loadProductsAndProcesses(this.form.operational_id);
          }
        } else {
          this.$modal.msgError("未找到该工艺路线信息");
        }
      }).catch(error => {
        console.error("获取工艺路线详情失败:", error);
        this.$modal.msgError("获取工艺路线详情失败");
      });
    },
    /** 提交按钮 */
    async submitForm() {
      this.$refs["form"].validate(async valid => {
        if (valid) {
          // 检查是否至少有一个产品
          if (!this.productList || this.productList.length === 0) {
            this.$modal.msgWarning("请至少添加一个产品");
            this.activeName = 'product'; // 切换到产品标签页
            return;
          }

          // 检查每个产品是否都有有效的产品ID
          const productsWithoutId = this.productList.filter(p => !(p.product_id || p.productId));
          if (productsWithoutId.length > 0) {
            this.$modal.msgWarning(`有 ${productsWithoutId.length} 个产品缺少有效ID，请检查产品数据`);
            this.activeName = 'product';
            return;
          }

          // 如果开启了自动编号，在提交前获取真正的编号
          if (this.isSystemCode) {
            try {
              const response = await getAutoNumbersConsume(32);
              if (response && response.msg) {
                this.form.operational_code = response.msg;
              } else if (typeof response === 'string') {
                this.form.operational_code = response;
              }
            } catch (error) {
              this.$message.error('获取最终工艺路线编号失败');
              return;
            }
          }

          // 记录提交前的产品数据
          console.log("提交前的产品列表:", this.productList.map(p => ({
            productId: p.product_id || p.productId,
            productName: p.product_name || p.productName,
            processList: p.processList ? p.processList.length : 0
          })));

          // 收集所有产品关联的工序
          let operatonaldetails = [];

          // 每个工序和产品的关联关系 - 使用数组形式
          let processProductPairs = [];

          // 检查每个产品是否有工序
          let hasProcesses = false;

          // 为每个产品添加工序关联
          this.productList.forEach(product => {
            // 确保获取正确的产品ID
            const productId = product.product_id || product.productId;
            if (!productId) {
              console.warn("产品缺少ID，跳过处理:", product);
              return;
            }

            if (product.processList && product.processList.length > 0) {
              hasProcesses = true;

              product.processList.forEach(process => {
                const processId = process.process_id;

                // 添加到关系数组 - 确保每个对象都包含 process_id 和 product_id
                processProductPairs.push({
                  process_id: processId,
                  product_id: productId
                });

                // 构造工序对象，同时包含下划线和驼峰命名的字段
                operatonaldetails.push({
                  // 下划线格式
                  process_id: processId,
                  product_id: productId,
                  // 驼峰格式
                  processId: processId,
                  productId: productId,
                  // 其他字段
                  sequence: process.sequence || '',
                  next_process_id: process.next_process_id || null,
                  next_process_name: process.next_process_name || '',
                  relation_type: process.relation_type || 'S-S',
                  is_key: process.is_key || 0,
                  prepare_time: process.prepare_time || 0,
                  wait_time: process.wait_time || 0,
                  color: process.color || '#1B9AEE',
                  remarks: process.remarks || '',
                  is_delete: "0",
                  process_code: process.process_code || '',
                  process_name: process.process_name || '',
                  // 添加删除的产品ID到每个对象中
                  deleteProductIds: this.deletedProductIds.length > 0 ? Number(this.deletedProductIds[0]) : null
                });
              });
            }
          });

          // 检查是否有工序
          if (!hasProcesses) {
            this.$modal.msgWarning("请为产品添加至少一个工序");
            this.activeName = 'product'; // 切换到产品标签页
            return;
          }

          // 打印关系数组，用于调试
          console.log("工序与产品关联数组:", JSON.stringify(processProductPairs));

          // 规范化产品列表，确保ID字段存在
          const productList = this.productList.map(product => {
            const productId = product.product_id || product.productId;
            return {
              // 下划线格式
              product_id: productId,
              product_code: product.product_code || product.productCode,
              product_name: product.product_name || product.productName,
              // 驼峰格式
              productId: productId,
              productCode: product.product_code || product.productCode,
              productName: product.product_name || product.productName,
              // 其他字段
              specification: product.specification || '',
              unit: product.unit || '',
              bom_code: product.bom_code || '--',
              bom_version: product.bom_version || '--'
            };
          });

          // 构建提交数据
          const submitData = {
            // 基本信息
            operational_id: this.form.operational_id, // 确保包含operational_id
            operational_name: this.form.operational_name,
            operational_code: this.form.operational_code,
            operational_status: this.form.operational_status,
            operational_description: this.form.operational_description,
            remarks: this.form.remarks,

            // 工序详情 - 使用两种可能的字段名
            operatonaldetails: operatonaldetails,
            operationaldetails: operatonaldetails,

            // 产品列表
            productList: productList,

            // 关系数组 - 确保每个对象包含process_id和product_id
            processProductRelations: processProductPairs
          };

          // 为了调试，打印完整提交数据
          console.log("提交的数据:", JSON.stringify(submitData));

          // 检查数据中的product_id字段
          console.log("操作明细中的产品ID:", operatonaldetails.map(o => o.product_id));
          console.log("删除的产品ID添加到每个operatonaldetails中:", operatonaldetails.map(o => o.deleteProductIds));
          console.log("已删除的产品ID:", this.deletedProductIds);
          console.log("已删除的产品ID类型:", typeof this.deletedProductIds, Array.isArray(this.deletedProductIds));
          console.log("第一个删除产品ID类型:", this.deletedProductIds.length > 0 ? typeof this.deletedProductIds[0] : 'none');
          console.log("submitData中的deleteProductId:", submitData.deleteProductId);

          if (this.form.operational_id) {
            // 如果是更新，需要传递operational_id
            submitData.operational_id = this.form.operational_id;

            // 如果是更新
            updateRoute(submitData).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              // 清空已删除的产品ID列表
              this.deletedProductIds = [];
              this.handleQuery();
            }).catch(error => {
              console.error("更新失败:", error);
            });
          } else {
            // 如果是新增，确保关系数据正确
            addRoute(submitData).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.handleQuery();
            }).catch(error => {
              console.error("新增失败:", error);
              console.error("请求失败的数据:", JSON.stringify(submitData));
            });
          }
        }
      });
    },
      /** 删除按钮操作 */
  handleDelete(row, batch = false) {
    const ids = row ? [row.operational_id] : this.ids;
    if (!ids || ids.length === 0) {
      this.$modal.msgWarning("请先选择要删除的工艺路线");
      return;
    }

    this.$modal.confirm('是否确认删除工艺路线编号为"' + (row ? row.operational_code : '所选') + '"的数据项?').then(() => {
      if (batch) {
        // 批量删除使用delRoutes方法
        return delRoutes(ids.join(','));
      } else {
        // 单个删除使用delRoute方法
        return delRoute(ids[0]);
      }
    }).then(() => {
      this.handleQuery();
      this.$modal.msgSuccess("删除成功");
    }).catch(() => {});
    },
    // 工序相关方法
    handleAddProcess() {
      this.processSelectVisible = true;
      this.processQuery.name = undefined; // 清空搜索框
      this.processQuery.pageNum = 1;
      this.getProcessOptions();
    },
    handleEditProcess(row) {
      this.processOpen = true;
      this.processActiveName = 'processBase'; // 切换到基本信息标签
      this.processTitle = '编辑工序';
      this.processForm = { ...row };
      if (!this.processOptions || this.processOptions.length === 0) {
        this.getProcessOptions();
      }
    },
    handleDeleteProcess(row) {
      this.$modal.confirm('是否确认删除该工序?').then(() => {
        // 从列表中删除该工序
        const index = this.processList.findIndex(item => item.process_id === row.process_id);
        if (index !== -1) {
          this.processList.splice(index, 1);
        }
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    handleProcessRowClick(row) {
      this.selectedProcess = row;
    },
    handleProcessSelectionChange(selection) {
      this.selectedProcess = selection.length === 1 ? selection[0] : null;
    },

    // 查看工艺路线详情
    handleViewDetail(row) {
      // 先调用API获取工艺路线详情
      listop1(row.operational_id).then(response => {
        // 将数据存储到sessionStorage中
        if (response.data) {
          sessionStorage.setItem('routeDetailData', JSON.stringify(response.data));
          console.log('工艺路线详情数据:', response.data);
        }

        // 跳转到详情页
        this.$router.push({
          path: `/sc/process/route-detail/${row.operational_id}`,
          query: { name: row.operational_name, code: row.operational_code }
        });
      }).catch(error => {
        this.$message.error("获取工艺路线详情失败");
        console.error("获取工艺路线详情失败:", error);
      });
    },
    // 处理工序选择变化
    handleProcessChange(val) {
      console.log("工序选择变化，选中值:", val);

      const process = this.processOptions.find(p => {
        const processId = p.process_id || p.processId;
        return processId === val;
      });

      console.log("找到的工序对象:", process);

      if (process) {
        this.processForm.process_code = process.process_code || process.processCode || '';
        this.processForm.process_name = process.process_name || process.processName || '';

        // 使用工序ID作为序号
        const processId = process.process_id || process.processId;
        this.processForm.sequence = processId.toString();

        console.log("已选择工序:", {
          id: val,
          name: this.processForm.process_name,
          code: this.processForm.process_code,
          sequence: this.processForm.sequence
        });

        // 如果是编辑模式，获取完整的工序信息
        if (this.title && this.title.includes('修改')) {
          console.log("编辑模式，获取详细工序信息");

          // 修改查询参数，确保正确传递process_id
          const query = {
            process_id: val,      // 使用snake_case格式
            pageNum: 1,           // 添加分页参数
            pageSize: 10          // 添加分页参数
          };

          console.log("发送查询参数:", query);

          this.processLoading = true;
          listProcess(query).then(response => {
            console.log("获取工序详情响应:", response);

            let processData = null;
            if (response && response.data) {
              processData = response.data;
            } else if (response && response.rows && response.rows.length > 0) {
              processData = response.rows[0];
            } else if (Array.isArray(response) && response.length > 0) {
              processData = response[0];
            }

            // 详细记录响应数据结构
            console.log("响应数据结构:", {
              hasData: !!response.data,
              hasRows: !!response.rows,
              rowsLength: response.rows ? response.rows.length : 0,
              firstRowFields: response.rows && response.rows.length > 0 ? Object.keys(response.rows[0]) : []
            });

            if (processData) {
              // 使用API返回的详细信息更新表单
              this.processForm.process_status = processData.process_status !== undefined ? processData.process_status : 1;
              this.processForm.process_description = processData.process_description || '';
              console.log("已加载工序状态:", this.processForm.process_status);
              console.log("已加载工序说明:", this.processForm.process_description);
            } else {
              console.warn("未能从响应中提取工序数据");
            }
          }).catch(error => {
            console.error("获取工序详情失败:", error);
          }).finally(() => {
            this.processLoading = false;
          });
        }
      } else {
        console.warn("未找到ID为", val, "的工序");
      }
    },

    // 处理工序多选变化
    handleProcessSelectChange(selection) {
      console.log("工序选择变化:", selection);
      // 保存选中的工序列表
      this.selectedProcesses = selection;
    },
    // 获取工序选项
    getProcessOptions() {
      this.processSelectLoading = true;

      // 构建查询参数
      const params = {
        processName: this.processQuery.name
      };

      listpro(params).then(response => {
        console.log("获取工序选项结果:", response);

        // 添加详细日志，查看响应结构
        console.log("响应类型:", typeof response);
        console.log("响应结构:", Object.keys(response));

        let processData = [];

        // 检查各种可能的响应格式
        if (response && response.data) {
          processData = response.data;
        } else if (response && response.rows) {
          processData = response.rows;
        } else if (Array.isArray(response)) {
          processData = response;
        } else if (response && typeof response === 'object') {
          // 如果response是一个对象但没有预期的字段，尝试从其他字段提取数据
          const possibleDataFields = ['data', 'rows', 'list', 'items', 'result'];
          for (const field of possibleDataFields) {
            if (response[field] && Array.isArray(response[field])) {
              processData = response[field];
              break;
            }
          }

          // 如果还是没找到，直接尝试使用response
          if (processData.length === 0 && !Array.isArray(response)) {
            processData = [response];
          }
        }

        console.log("提取的工序数据:", processData);

        // 确保我们处理的是数组
        if (Array.isArray(processData)) {
          // 格式化数据，确保字段名一致
          this.processOptions = processData.map(item => {
            // 检查字段是否存在，并使用标准化的字段名
            return {
              process_id: item.process_id || item.processId,
              processId: item.process_id || item.processId,
              process_code: item.process_code || item.processCode,
              processCode: item.process_code || item.processCode,
              process_name: item.process_name || item.processName,
              processName: item.process_name || item.processName,
              process_description: item.process_description || item.processDescription,
              process_status: item.process_status || item.processStatus,
              station_id: item.station_id || item.stationId
            };
          });

          this.processSelectList = [...this.processOptions];
          this.processSelectTotal = this.processOptions.length;

          console.log("格式化后的工序选项:", this.processOptions);
        } else {
          console.error("无法提取工序数据:", processData);
          this.processOptions = [];
          this.processSelectList = [];
          this.processSelectTotal = 0;
        }
      }).catch(error => {
        console.error("获取工序选项失败:", error);
        this.processOptions = [];
        this.processSelectList = [];
        this.processSelectTotal = 0;
      }).finally(() => {
        this.processSelectLoading = false;
      });
    },
    // 获取工序列表数据
    getProcessList() {
      this.getProcessOptions();
    },
    searchProcess() {
      this.processQuery.pageNum = 1;
      this.getProcessOptions();
    },
    resetProcessQuery() {
      this.processQuery.name = undefined;
      this.processQuery.pageNum = 1;
      this.getProcessOptions();
    },
    confirmSelectProcess() {
      const selectedProcesses = this.$refs.processSelectTable ? this.$refs.processSelectTable.selection : [];
      if (selectedProcesses.length > 0) {
        // 检查是否有当前产品
        if (this.currentProduct) {
          // 如果是为特定产品添加工序
          if (!this.currentProduct.processList) {
            this.$set(this.currentProduct, 'processList', []);
          }

          selectedProcesses.forEach(process => {
            // 确保不添加重复工序
            if (!this.currentProduct.processList.some(p => p.process_id === process.process_id)) {
              this.currentProduct.processList.push({
                process_id: process.process_id,
                process_code: process.process_code,
                process_name: process.process_name,
                next_process_id: null,
                next_process_name: '无下道工序',
                relation_type: 0,
                is_key: 0,
                prepare_time: 0,
                wait_time: 0,
                color: '#409EFF'
              });
            }
          });

          // 添加成功提示
          this.$modal.msgSuccess(`已为产品 ${this.currentProduct.product_name} 添加工序`);
          this.currentProduct = null; // 清空当前产品
        } else {
          // 如果是直接添加工序到工艺路线
          selectedProcesses.forEach(process => {
            // 确保不添加重复工序
            if (!this.processList.some(p => p.process_id === process.process_id)) {
              this.processList.push({
                process_id: process.process_id,
                process_code: process.process_code,
                process_name: process.process_name,
                next_process_id: null,
                next_process_name: '无下道工序',
                relation_type: 0,
                is_key: 0,
                prepare_time: 0,
                wait_time: 0,
                color: '#409EFF'
              });
            }
          });
        }
        this.processSelectVisible = false;
      } else {
        this.$modal.msgWarning("请至少选择一个工序");
      }
    },
    // 产品相关方法
    handleAddProduct() {
      this.productSelectVisible = true;
      this.productQuery = {
        pageNum: 1,
        pageSize: 10,
        name: undefined
      };
      // 清空之前的选择
      this.selectedProducts = [];
      this.getProductList();
    },
    handleRemoveProduct(row) {
      const productToRemove = row || this.selectedProduct;

      if (productToRemove) {
        this.$modal.confirm('是否确认移除该产品?').then(() => {
          // 判断是否为修改模式，如果是且有产品ID，则添加到删除列表
          if (this.title.includes('修改') && productToRemove.product_id) {
            const productId = Number(productToRemove.product_id); // 转换为数字类型
            console.log("记录删除的产品ID:", productId, "类型:", typeof productId);

            // 清空原数组，只保留最新删除的产品ID
            this.deletedProductIds = [productId];

            // 在控制台显示当前删除的产品ID列表，用于调试
            console.log("当前deletedProductIds:", this.deletedProductIds);
            console.log("当前deletedProductIds(JSON):", JSON.stringify(this.deletedProductIds));
          }

          // 从列表中删除该产品
          const index = this.productList.findIndex(item => item.product_id === productToRemove.product_id);
          if (index !== -1) {
            this.productList.splice(index, 1);
          }
          this.$modal.msgSuccess("移除成功");
          if (!row) { // 如果是通过批量删除按钮移除，需要清空选择
            this.selectedProduct = null;
          }
        }).catch(() => {});
      } else {
        this.$modal.msgWarning("请先选择要移除的产品");
      }
    },
    handleProductRowClick(row) {
      this.selectedProduct = row;
    },
    handleProductSelectionChange(selection) {
      console.log("产品选择变化:", selection);
      this.selectedProduct = selection.length === 1 ? selection[0] : null;
      this.selectedProducts = selection;
    },
    // 处理产品选择变化
    handleProductSelectChange(selection) {
      console.log("产品选择对话框选择变化，选中数量:", selection.length);

      // 详细记录每个选中产品的信息
      selection.forEach((item, index) => {
        const productId = item.product_id || item.productId;
        console.log(`选中产品 ${index+1}:`, {
          名称: item.product_name || item.productName,
          ID: productId,
          编号: item.product_code || item.productCode
        });

        // 如果发现没有ID的产品，记录警告
        if (!productId) {
          console.warn("警告：选中的产品缺少ID:", item);
        }
      });

      // 保存选中的产品列表，确保所有关键字段都有值
      this.selectedProducts = selection.map(item => {
        const productId = item.product_id || item.productId;
        const productCode = item.product_code || item.productCode;
        const productName = item.product_name || item.productName;

        // 返回规范化的产品对象
        return {
          ...item, // 保留原始字段
          // 确保snake_case格式字段
          product_id: productId,
          product_code: productCode,
          product_name: productName,
          // 确保camelCase格式字段
          productId: productId,
          productCode: productCode,
          productName: productName
        };
      });

      // 记录选中产品的ID列表
      const productIds = this.selectedProducts.map(p => p.product_id).filter(Boolean);
      console.log("选中的产品ID列表:", productIds);
    },
    getProductList() {
      this.productSelectLoading = true;
      const query = {
        pageNum: this.productQuery.pageNum,
        pageSize: this.productQuery.pageSize,
        productName: this.productQuery.name // 使用name作为产品名称的查询参数
      };

      // 添加日志以查看后端返回的数据
      console.log("请求未关联工艺路线的产品数据，参数:", query);

      // 创建当前产品ID和产品编号的集合，用于快速查找
      const existingProductIds = new Set(this.productList.map(p => p.product_id).filter(Boolean));
      const existingProductCodes = new Set(this.productList.map(p => p.product_code).filter(Boolean));

      listBomdetailsVoByOperationalIdIsNull(query).then(response => {
        console.log("后端返回的未关联工艺路线的产品数据:", response);

        // 处理返回数据
        if (response && response.rows) {
          const rows = response.rows;
          console.log("API返回的产品行数:", rows.length);

          // 记录第一条数据的字段，用于调试
          if (rows.length > 0) {
            const firstRow = rows[0];
            console.log("第一条产品数据的字段:", Object.keys(firstRow));
            console.log("第一条产品数据:", firstRow);
          }

          // 处理并规范化每条产品数据
          this.productSelectList = rows.map(item => {
            // 确保同时获取snake_case和camelCase格式的ID
            const productId = item.product_id || item.productId || '';

            // 日志记录，用于调试
            console.log(`处理产品: ${item.product_name || item.productName}, ID: ${productId}`);

            // 检查产品是否已经在产品列表中
            const isAlreadySelected =
              (productId && existingProductIds.has(productId)) ||
              (item.product_code && existingProductCodes.has(item.product_code));

            // 返回规范化的对象，确保所有关键字段都有值
            return {
              ...item, // 保留原始字段
              // 确保snake_case格式的字段
              product_id: productId,
              product_code: item.product_code || item.productCode || '',
              product_name: item.product_name || item.productName || '',
              specification: item.specification || item.product_sfn || '',
              unit: item.unit || item.product_unit || '',
              bom_code: item.bom_code || item.bomCode || '--',
              bom_version: item.bom_version || item.bomVersion || '--',
              // 同时确保camelCase格式的字段
              productId: productId,
              productCode: item.product_code || item.productCode || '',
              productName: item.product_name || item.productName || '',
              // 是否已选
              isAlreadySelected
            };
          });

          this.productSelectTotal = response.total || rows.length || 0;

          // 打印处理后的数据
          console.log("处理后的产品数据:", this.productSelectList.map(p => ({
            product_id: p.product_id,
            product_name: p.product_name
          })));
        } else {
          console.warn("API返回数据格式不符合预期:", response);
          this.productSelectList = [];
          this.productSelectTotal = 0;
        }
      }).catch(error => {
        console.error("获取产品数据失败:", error);
        this.productSelectList = [];
        this.productSelectTotal = 0;
      }).finally(() => {
        this.productSelectLoading = false;
      });
    },
    // 产品搜索
    searchProduct() {
      this.productQuery.pageNum = 1;
      this.getProductList();
    },
    resetProductQuery() {
      this.productQuery = {
        pageNum: 1,
        pageSize: 10,
        name: undefined
      };
      this.getProductList();
    },
    // 辅助方法：记录产品列表状态
    logProductListState() {
      // 检查产品列表的详细信息
      const productDetails = this.productList.map((p, index) => {
        return {
          序号: index + 1,
          产品ID: p.product_id || p.productId,
          驼峰格式ID: p.productId,
          产品名称: p.product_name || p.productName,
          产品编号: p.product_code || p.productCode,
          工序数量: p.processList ? p.processList.length : 0,
          是否有效: Boolean(p.product_id || p.productId)
        };
      });

      console.log("当前产品列表状态:", {
        产品数量: this.productList.length,
        产品列表有效性: this.productList.every(p => Boolean(p.product_id || p.productId)),
        产品列表: productDetails
      });

      // 检查是否有产品缺少ID
      const missingIds = this.productList.filter(p => !(p.product_id || p.productId));
      if (missingIds.length > 0) {
        console.warn("发现缺少ID的产品:", missingIds);
      }
    },

    confirmSelectProduct() {
      if (!this.selectedProducts || this.selectedProducts.length === 0) {
        this.$modal.msgWarning("请至少选择一个产品");
        return;
      }

      console.log("选中的产品数据:", this.selectedProducts, "数量:", this.selectedProducts.length);

      // 记录每个选中产品的ID情况
      this.selectedProducts.forEach((product, index) => {
        console.log(`选中产品 ${index+1}:`, {
          产品名称: product.product_name || product.productName,
          产品ID: product.product_id || product.productId,
          产品编号: product.product_code || product.productCode
        });
      });

      // 使用一个计数器来追踪添加了多少个新产品
      let addedCount = 0;
      // 追踪已经存在的产品数量
      let existingCount = 0;

      // 创建当前产品ID和产品编号的集合，用于快速查找
      const existingProductIds = new Set(this.productList.map(p => p.product_id).filter(Boolean));
      const existingProductCodes = new Set(this.productList.map(p => p.product_code).filter(Boolean));

      // 使用一个数组来存储所有要添加的产品，确保全部添加
      const productsToAdd = [];

      this.selectedProducts.forEach(product => {
        // 确保获取正确的产品ID和其他字段
        const productId = product.product_id || product.productId;
        if (!productId) {
          console.warn("产品缺少ID，跳过添加:", product);
          return;
        }

        const productCode = product.product_code || product.productCode;
        const productName = product.product_name || product.productName;

        console.log(`处理产品 ${productName}:`, {
          ID: productId,
          编号: productCode
        });

        // 检查产品是否已经存在于列表中
        const isDuplicate =
          (productId && existingProductIds.has(productId)) ||
          (productCode && existingProductCodes.has(productCode));

        if (!isDuplicate) {
          // 构建新产品对象，同时保存snake_case和camelCase格式的字段
          const newProduct = {
            // snake_case格式
            product_id: productId,
            product_code: productCode,
            product_name: productName,
            specification: product.specification || product.product_sfn || '',
            unit: product.unit || product.product_unit || '',
            bom_code: product.bom_code || product.bomCode || '--',
            bom_version: product.bom_version || product.bomVersion || '--',
            // camelCase格式
            productId: productId,
            productCode: productCode,
            productName: productName,
            // 其他字段
            processList: [] // 为产品添加工序列表属性
          };

          console.log("新增产品数据:", newProduct);
          productsToAdd.push(newProduct);
          addedCount++;
        } else {
          console.log(`产品 ${productName} 已存在于列表中，跳过添加`);
          existingCount++;
        }
      });

      // 将所有产品一次性添加到产品列表中
      if (productsToAdd.length > 0) {
        // 创建新数组以确保Vue能够检测到变化
        const newProductList = [...this.productList, ...productsToAdd];

        // 强制Vue更新产品列表
        this.$set(this, 'productList', newProductList);

        // 记录更新后的产品列表状态
        this.logProductListState();

        // 显示成功消息，包含添加的产品数量
        this.$modal.msgSuccess(`成功添加${addedCount}个产品`);
      } else if (existingCount > 0) {
        // 如果所有选中的产品都已存在，显示相应提示
        this.$modal.msgWarning(`您选择的${existingCount}个产品已经在列表中，无需重复添加`);
      }

      this.productSelectVisible = false;
      // 清空选中状态
      this.selectedProducts = [];
      if (this.$refs.productSelectTable) {
        this.$refs.productSelectTable.clearSelection();
      }
    },

    // 为产品添加工序
    handleAddProcessForProduct(product) {
      // 保存当前操作的产品
      this.currentProduct = product;

      // 先获取工序选项，确保下拉框有数据
      this.getProcessOptions();

      // 打开添加工序对话框
      this.processOpen = true;
      this.processTitle = `为产品 ${product.product_name} 添加工序`;

      // 记录当前是否是编辑模式
      console.log("当前操作模式:", this.title.includes('修改') ? "修改模式" : "新增模式");

      // 重置工序表单
      this.processForm = {
        process_id: undefined,
        process_name: undefined,
        process_code: undefined,
        sequence: '', // 初始为空，将在选择工序后自动填充
        next_process_id: null,
        next_process_name: '无下道工序',
        relation_type: 'S-S',
        is_key: 0,
        prepare_time: 0,
        wait_time: 0,
        color: '#1B9AEE',
        remarks: '',
        product_id: product.product_id,  // 关联产品ID
        process_status: 1,               // 工序状态，默认为启用
        process_description: ''          // 工序说明
      };
    },
    // 步骤切换
    prev() {
      this.active--;
    },
    next() {
      if (this.activeName === 'base') {
        this.$refs["form"].validate(valid => {
          if (valid) {
            this.activeName = 'process';
          }
        });
      } else if (this.activeName === 'base') {
        this.activeName = 'product';
      } else if (this.activeName === 'product') {
        if (this.productList.length > 0) {
          this.activeName = 'base'; // 回到基本信息
          this.$refs["form"].validate(valid => {
            if (valid) {
              this.active = 0; // 回到基本信息步骤
            }
          });
        } else {
          this.$modal.msgWarning("请先添加产品");
        }
      }
    },
    // 工序编辑对话框方法
    cancelProcess() {
      this.processOpen = false;
      this.processForm = {
        process_id: undefined,
        process_name: undefined,
        process_code: undefined,
        sequence: '', // 初始为空，将在选择工序后自动填充
        next_process_id: null,
        next_process_name: '无下道工序',
        relation_type: 'S-S',
        is_key: 0,
        prepare_time: 0,
        wait_time: 0,
        color: '#1B9AEE',
        remarks: '',
        process_status: 1,
        process_description: ''
      };
      this.currentProduct = null; // 清空当前产品
      this.processOptions = []; // 清空选项
    },
    submitProcessForm() {
      this.$refs["processForm"].validate(valid => {
        if (valid) {
          // 检查是否是编辑模式
          const isEditMode = this.title.includes('修改');

          if (isEditMode) {
            // 编辑模式：先获取完整的工序信息
            // 修改查询参数，确保正确传递process_id
            const query = {
              process_id: this.processForm.process_id,  // 使用snake_case格式
              pageNum: 1,                               // 添加分页参数
              pageSize: 10                              // 添加分页参数
            };

            console.log("提交时发送查询参数:", query);

            this.processLoading = true;
            listProcess(query).then(response => {
              console.log("获取工序详情响应:", response);

              let processData = null;
              if (response && response.data) {
                processData = response.data;
              } else if (response && response.rows && response.rows.length > 0) {
                processData = response.rows[0];
              } else if (Array.isArray(response) && response.length > 0) {
                processData = response[0];
              }

              // 详细记录响应数据结构
              console.log("提交时响应数据结构:", {
                hasData: !!response.data,
                hasRows: !!response.rows,
                rowsLength: response.rows ? response.rows.length : 0,
                firstRowFields: response.rows && response.rows.length > 0 ? Object.keys(response.rows[0]) : []
              });

              if (processData) {
                // 构建工序对象，结合API返回的详情和表单数据
          const process = {
            process_id: this.processForm.process_id,
                  process_code: processData.process_code || this.processForm.process_code,
                  process_name: processData.process_name || this.processForm.process_name,
            sequence: this.processForm.sequence,
            next_process_id: this.processForm.next_process_id,
                  next_process_name: this.processForm.next_process_name || '无下道工序',
            relation_type: this.processForm.relation_type,
            is_key: this.processForm.is_key,
            prepare_time: this.processForm.prepare_time,
            wait_time: this.processForm.wait_time,
            color: this.processForm.color,
            remarks: this.processForm.remarks,
                  product_id: this.processForm.product_id,
                  process_status: processData.process_status !== undefined ? processData.process_status : 1,
                  process_description: processData.process_description || ''
                };

                // 添加到当前产品
                if (this.currentProduct) {
                  if (!this.currentProduct.processList) {
                    this.$set(this.currentProduct, 'processList', []);
                  }

                  // 将工序添加到列表末尾，确保显示在表格最下方
                  this.currentProduct.processList.push(process);

                  // 更新工序间的关系
                  this.updateProductProcessRelationships(this.currentProduct);

                  this.$modal.msgSuccess(`已为产品 ${this.currentProduct.product_name} 添加工序`);
                  this.currentProduct = null;
          } else {
                  this.processList.push(process);
                }

                this.processOpen = false;
              } else {
                this.$modal.msgError("获取工序详情失败");
              }
            }).catch(error => {
              console.error("获取工序详情失败:", error);
              this.$modal.msgError("获取工序详情失败，请查看控制台错误信息");
            }).finally(() => {
              this.processLoading = false;
            });
          } else {
            // 非编辑模式：使用原来的逻辑
            // 构建工序对象
            const process = {
              process_id: this.processForm.process_id,
              process_code: this.processForm.process_code,
              process_name: this.processForm.process_name,
              sequence: this.processForm.sequence,
              next_process_id: this.processForm.next_process_id,
              next_process_name: this.processForm.next_process_name || '无下道工序',
              relation_type: this.processForm.relation_type,
              is_key: this.processForm.is_key,
              prepare_time: this.processForm.prepare_time,
              wait_time: this.processForm.wait_time,
              color: this.processForm.color,
              remarks: this.processForm.remarks,
              product_id: this.processForm.product_id
            };

          // 如果是为特定产品添加工序
          if (this.currentProduct) {
            // 确保产品有工序列表属性
            if (!this.currentProduct.processList) {
              this.$set(this.currentProduct, 'processList', []);
            }

            // 添加工序到产品的工序列表
            this.currentProduct.processList.push(process);

            // 在新增模式下，也更新工序间的关系
            this.updateProductProcessRelationships(this.currentProduct);

            // 显示成功消息
            this.$modal.msgSuccess(`已为产品 ${this.currentProduct.product_name} 添加工序`);

            // 清空当前产品
            this.currentProduct = null;
          } else {
            // 否则添加到全局工序列表
            this.processList.push(process);
          }

          // 关闭对话框
          this.processOpen = false;
          }
        }
      });
    },
    // 生成工序编号
    generateProcessCode() {
      getAutoNumbers(32).then(response => {
        if (response && typeof response === 'string') {
          this.processForm.process_code = response;
        } else if (response && response.data) {
          this.processForm.process_code = response.data;
        } else {
          this.processForm.process_code = "GONGXU" + new Date().getTime();
        }
      });
    },
    // 获取行类名
    getRowClassName({ row, rowIndex }) {
      if (row.isAlreadySelected) {
        return 'already-selected-row';
      }
      return '';
    },
    // 移除工序
    handleRemoveProcess(product, process) {
      this.$modal.confirm(`是否确认移除工序 "${process.process_name}" 吗?`).then(() => {
        // 从产品的工序列表中移除
        const index = product.processList.findIndex(p => p.process_id === process.process_id);
        if (index !== -1) {
          product.processList.splice(index, 1);
        }
        this.$modal.msgSuccess("移除成功");
      }).catch(() => {});
    },
    // 处理标签页点击事件
    handleTabClick(tab) {
      if (tab.name === 'product') {
        // 当切换到"关联产品"标签页时，如果是编辑模式并且有operational_id，则加载产品数据
        if (this.form.operational_id) {
          this.loadProductsAndProcesses(this.form.operational_id);
        }
      }
    },
    handleNextProcessChange(value) {
      console.log("下一道工序选择变化:", value);

      if (value) {
        // 查找选中的下一道工序
        const nextProcess = this.processOptions.find(p => (p.process_id || p.processId) === value);
        if (nextProcess) {
          // 设置下一道工序名称
          this.processForm.next_process_name = nextProcess.process_name || nextProcess.processName;
          console.log("设置下一道工序名称为:", this.processForm.next_process_name);
        }
      } else {
        // 如果没有选择下一道工序，设置为"无下道工序"
        this.processForm.next_process_name = '无下道工序';
      }
    },
    getProcessStatusType(status) {
      // 将status转换为数字，确保比较的一致性
      const numStatus = Number(status);

      if (isNaN(numStatus)) {
        return 'info';
      }

      switch (numStatus) {
        case 0:
          return 'danger';
        case 1:
          return 'success';
        case 2:
          return 'warning';
        default:
          return 'info';
      }
    },
    getProcessStatusText(status) {
      // 将status转换为数字，确保比较的一致性
      const numStatus = Number(status);

      if (isNaN(numStatus)) {
        return '未设置';
      }

      switch (numStatus) {
        case 0:
          return '停用';
        case 1:
          return '启用';
        case 2:
          return '暂停';
        default:
          return `状态${numStatus}`;
      }
    },
    // 更新产品的工序关系
    updateProductProcessRelationships(product) {
      if (!product || !product.processList || product.processList.length === 0) {
        return;
      }

      // 按照列表顺序更新工序关系
      for (let i = 0; i < product.processList.length; i++) {
        const currentProcess = product.processList[i];
        if (i < product.processList.length - 1) {
          // 不是最后一个工序，下一道工序是列表中的下一个
          currentProcess.next_process_name = product.processList[i + 1].process_name;
        } else {
          // 最后一个工序，没有下一道工序
          currentProcess.next_process_name = '无下道工序';
        }
      }
    },
    // 特殊的数据转换方法，确保productId为数字类型
    formatProductId(id) {
      if (id === null || id === undefined) return null;

      // 尝试将ID转换为数字
      let numId;
      try {
        numId = Number(id);
        if (isNaN(numId)) {
          console.warn("产品ID无法转换为数字:", id);
          return id; // 如果无法转换，保持原值
        }
        return numId;
      } catch (error) {
        console.error("转换产品ID时出错:", error);
        return id;
      }
    },
    handleSystemCodeChange(val) {
      if (val) {
        // 如果开启系统编号，则生成编号
        this.generateRouteCode();
      } else {
        // 如果关闭系统编号，则清空编号
        this.form.operational_code = '';
      }
    },
  }
};
</script>

<style scoped>
.search-form {
  padding: 15px;
  background: #fff;
  border-radius: 5px;
  margin-bottom: 20px;
}

.title-container {
  margin-bottom: 15px;
}

.title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  padding-left: 10px;
  border-left: 4px solid #409EFF;
}

.mb8 {
  margin-bottom: 8px;
}

.blue-text {
  color: #409EFF;
}

.red-text {
  color: #F56C6C;
}

/* 新增样式 */
.el-tabs__header {
  margin-bottom: 20px;
}

.el-tabs__item {
  font-size: 16px;
  height: 50px;
  line-height: 50px;
}

.auto-code-btn {
  position: absolute;
  right: 10px;
  top: 0;
}

.el-form-item {
  margin-bottom: 25px;
}

.el-input-number {
  width: 100%;
}

.error-tip {
  line-height: 1;
  position: relative;
  margin-top: 5px;
}

/* 对话框样式 */
.el-dialog {
  border-radius: 8px;
}

.el-dialog__header {
  padding: 15px 20px;
  border-bottom: 1px solid #eee;
}

.el-dialog__body {
  padding: 20px 30px;
}

.el-dialog__footer {
  padding: 15px 20px;
  border-top: 1px solid #eee;
}

.el-form-item__label {
  color: #333;
  font-weight: 500;
}

/* 新增样式：已选择产品的行样式 */
.already-selected-row {
  background-color: #f5f7fa; /* 浅灰色背景 */
}

/* 工序表单样式 */
.time-unit {
  margin-left: 10px;
  color: #606266;
}

.el-color-picker {
  vertical-align: middle;
}

.time-input-container {
  display: flex;
  align-items: center;
}

/* 给必填项添加红色星号 */
.el-form-item.is-required .el-form-item__label:before {
  content: '*';
  color: #F56C6C;
  margin-right: 4px;
}

/* 控制输入框的高度和边距 */
.el-input-number.is-controls-right .el-input__inner {
  padding-right: 50px;
  text-align: center;
}

/* 无数据提示 */
.no-data {
  padding: 30px 0;
  text-align: center;
  color: #909399;
  font-size: 14px;
  background-color: #f8f8f9;
}

/* 嵌套表格样式 */
.el-table .el-table__expanded-cell {
  padding: 20px 50px;
  background-color: #f8f8f9;
}

/* 工序表格中颜色显示样式 */
.color-box {
  display: inline-block;
  width: 20px;
  height: 20px;
  margin-right: 5px;
  border-radius: 4px;
  vertical-align: middle;
}
</style>
